import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {routerTransition} from '../router.animations';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {Md5} from "ts-md5/dist/md5";
import {Http, Headers, RequestOptions, Response} from '@angular/http';
import {RestEntity} from "../../domain/RestEntity";
import {HttpService} from "../../providers/http-service";
import {User} from "../../domain/User";
import {Constants} from "../../domain/Constants";
import {StorageService} from "../../providers/storage-service";

@Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.scss'],
    animations: [routerTransition()],

})
export class LoginComponent implements OnInit {
    myForm: FormGroup;
    username: string;
    password: string;
    data: RestEntity;
    // user: User;

    constructor(public router: Router, fb: FormBuilder, private httpService: HttpService,public storageService:StorageService,) {
        this.myForm = fb.group({
            'username': ['', Validators.required],
            'password': ['', Validators.required]
        });
    }

    ngOnInit() {
        this.myForm.valueChanges.subscribe(data => this.onValueChanged(data));
    }
    //存储错误信息
    formErrors = {
        'username': '',
        'password': '',
    };
    //错误对应的提示
    validationMessages = {
        'username': {
            'required': '用户名必填.',
            'minlength': '至少4个字符',
            'maxlength': '最多8个字符',
        },
        'password':{
            'required': '请输入密码',
            'minlength': '至少4个字符',
            'maxlength': '最多8个字符',
        },
    };
    /**
     * 表单值改变时，重新校验
     * @param data
     */
    onValueChanged(data) {
        for (const field in this.formErrors) {
            this.formErrors[field] = '';
            //取到表单字段
            const control = this.myForm.get(field);
            //表单字段已修改或无效
            if (control && control.dirty && !control.valid) {
                //取出对应字段可能的错误信息
                const messages = this.validationMessages[field];
                //从errors里取出错误类型，再拼上该错误对应的信息
                for (const key in control.errors) {
                    this.formErrors[field] += messages[key] + '';
                }
            }

        }

    }
    onLoggedin(value: string) {
        localStorage.setItem('isLoggedin', 'true');
        console.log('you submitted value: ', value);
        let param = "username=" + this.username + "&password=" + this.password;
        this.httpService.httpPostLoginForm("login", param,this.username,this.password).then(restEntity => {
            // console.log(restEntity);
            if (restEntity.status == 1) {
                let user:User = restEntity.object;
                this.storageService.write(Constants.CURR_USER,user);
                console.log(this.httpService.getRoleCode());
                this.router.navigate(['/dashboard']);
            }
        }).catch(
            error => {
            }
        );
    }
}
